package org.poxd.persistance;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

/**
 * Factory class used to manage the hibernate's session opening/closing
 * 
 * @author pollux
 * 
 */
public class SessionService {
	private static SessionFactory sessionFactory;
	private static Session session;

	static {
		try {
			sessionFactory = new Configuration().configure()
					.buildSessionFactory();
		} catch (HibernateException e) {
			throw new SniwePersistanceException(e);
		}
	}

	/**
	 * Opens a session
	 * 
	 * @return the opened session
	 * @throws SniwePersistanceException
	 */
	public static Session getSession() throws SniwePersistanceException {
		if (session == null) {
			try {
				session = sessionFactory.openSession();
			} catch (HibernateException e) {
				throw new SniwePersistanceException(e);
			}
		}
		return session;
	}

	/**
	 * Close a session
	 * 
	 * @throws SniwePersistanceException
	 */
	public static void closeSession() throws SniwePersistanceException {
		if (session != null) {
			try {
				session.close();
			} catch (HibernateException e) {
				throw new SniwePersistanceException(e);
			}
		}
	}

}
